package com.wind.bdg.middlewarelearndemo.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.classification.InterfaceAudience.Public;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wind.bdg.middlewarelearndemo.model.News;
import com.wind.bdg.middlewarelearndemo.service.ESService;
import com.wind.bdg.middlewarelearndemo.service.RedisService;
import com.wind.bdg.middlewarelearndemo.util.App;

@RestController
public class QueryController {
	@Autowired
	private RedisService redisService;
	
	@Autowired
	private ESService eSService;
	
	@GetMapping("/init")
	public void init() throws Exception {
		App app = new App();
		List listTitle = app.getTitle("<td>《*[0-9]*[\\u4e00-\\u9fa5]+.*?</td>");
		List listTime = app.getTime("<td>2020-.*?</td>");
		List listId = app.getUrl("http://10.202.32.15/medicine/medicine/webNewsList.do");
		List<String[]> list = new ArrayList<String[]>();
		for(int i=0;i<listTitle.size();i++) {
			String[] tem = new String[4];
			tem[0]=(String) listId.get(i);
			tem[1]=(String) listTitle.get(i);
			tem[2]=(String) listTime.get(i);
			tem[3]="网页详情内容";
			list.add(tem);
		}
		
		//初始化数据进入es
		eSService.createIndex("study_news_21732");
		eSService.addMapping("study_news_21732", "study_news_21732");
		for(String[] tem:list) {
			String id=tem[0];
			String title=tem[1];
			String time=tem[2];
			String content=tem[3];
			News news = new News(id, title, time, content);
//			eSService.delete("study_news_21732", "study_news_21732","21732"+news.getId());
			eSService.add("study_news_21732", "study_news_21732", news);
		}
		
		//初始化数据进入redis
		for(String[] tem:list){
			String id=tem[0];
			String title=tem[1];
			String time=tem[2];
			String content=tem[3];
			Map< String, Object> map = new HashMap();
			map.put("id", id);
			map.put("title", title);
			map.put("time", time);
			map.put("content", content);
			redisService.hmset("21732"+id, map);
			
		}
	} 
	
	/**
	 * 
	 * @Title:  QueryController   
	 * @Description:    查询redis是否存在，不存在则从es中读取并写入redis  
	 * @param:  @param id  
	 * @throws
	 */
	@GetMapping("/query/{id}")
	public void method(@PathVariable String id) {
		if(redisService.hmget(id)!=null) {
			System.out.println(redisService.hmget("21732"+id));
		}else {
			//已经将redisService.hmset("21732"+id, map)写进下面的方法;
			eSService.query("study_news_21732", "study_news_21732","21732"+id);
					
		}
	}
	
}
